package com.fany.fastsearcher.activity;

import com.fany.filesearcher.FileLoadController;
import com.fany.filesearcher.SQLiteFileRecorder;
import com.fany.utils.CommonUtils;
import com.fany.utils.ConfigUtils;
import com.fany.utils.FileHelper;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * Created by FANY on 2015/1/29.
 */
public class FileSearchDataController
{
    private String _filter = "";
    private String _lastFilter = "";
    private boolean _isSearching = false;

    private SQLiteFileRecorder _recorder;
    private FileSearchActivity _activity;

    public void setFilter(String filter)
    {
        _filter = filter;
    }

    public static FileSearchDataController loadDataController(FileSearchActivity activity)
    {
        return new FileSearchDataController(activity);
    }

    private FileSearchDataController(FileSearchActivity activity)
    {
        _activity = activity;
        _recorder = new SQLiteFileRecorder(_activity);
        if (_recorder.hasLoaded())
        {
            CommonUtils.showToast(activity, String.format("当前缓存%d条数据", _recorder.getRecordCount()));
        }
        else
        {
            loadData();
        }
    }

    public void loadData()
    {
        new FileLoadController(_activity, _recorder).loadFiles();
        ConfigUtils.getInstance().setNeedReloadCache(false);
    }

    public boolean initData(ArrayList<HashMap<String, Object>> items, boolean forceReload)
    {
        if (_isSearching || (_filter.equals(_lastFilter) && !forceReload))
        {
            return false;
        }
        items.clear();
        if (_filter.isEmpty())
        {
            return false;
        }
        items.addAll(getResults(false));
        _isSearching = false;
        _lastFilter = _filter;
        return true;
    }

    public void appendData(ArrayList<HashMap<String, Object>> items)
    {
        if (_isSearching || _filter.isEmpty())
        {
            return;
        }
        items.addAll(getResults(true));
        _isSearching = false;
        _lastFilter = _filter;
    }

    private ArrayList<HashMap<String, Object>> getResults(boolean append)
    {
        ArrayList<HashMap<String, Object>> results = new ArrayList<HashMap<String, Object>>();
        List<String> items = new ArrayList<String>();
        if (_filter.length() > 0)
        {
            _filter = _filter.replace("*", "%%");
            items.addAll(_recorder.searchFile(_filter, append));
        }
        for (int i = 0; i < items.size(); i++)
        {
            HashMap<String, Object> map = new HashMap<String, Object>();
            map.put("filename", FileHelper.extractFileName(items.get(i)));
            map.put("fullpath", items.get(i));
            results.add(map);
        }
        return results;
    }
}
